package com.tanhua.server.service;

import cn.hutool.core.collection.CollectionUtil;
import com.tanhua.dubbo.api.db.UserInfoApi;
import com.tanhua.dubbo.api.mongo.CommentApi;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.enums.CommentType;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.vo.CommentVo;
import com.tanhua.model.vo.PageResult;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class CommentsService {

    @DubboReference
    private CommentApi commentApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    /**
     * 对某个动态的评论分页列表
     * @param page
     * @param pagesize
     * @param movementId
     * @return
     */
    public PageResult commentList(Long page, Long pagesize, String movementId) {
        //1. 通过动态id，分页查询评论列表
        PageResult pageResult = commentApi.findPage(page,pagesize,movementId);
        //2. 获取评论者ids
        //2.1 获取评论列表
        List<Comment> commentList = pageResult.getItems();
        List<CommentVo> voList = new ArrayList<>();
        //2.2 判断是否有数据, 有可以超过页码
        if(CollectionUtil.isNotEmpty(commentList)) {
            List<Long> userIds = commentList.stream().map(Comment::getUserId).collect(Collectors.toList());
            //3. 查询评论者信息
            Map<Long, UserInfo> userInfoMap = userInfoApi.findByBatchIds(userIds, null);
            //4. 转成vo
            voList = commentList.stream().map(c -> CommentVo.init(userInfoMap.get(c.getUserId()), c)).collect(Collectors.toList());
        }
        //5. 设置到pageResult
        pageResult.setItems(voList);
        //6. 返回
        return pageResult;
    }

    /**
     * 发表评论
     * @param paramMap
     */
    public void add(Map<String, String> paramMap) {
        // 构建pojo
        Comment pojo = new Comment();
        // 设置属性
        pojo.setPublishId(new ObjectId(paramMap.get("movementId")));
        pojo.setCommentType(CommentType.COMMENT.getType());
        pojo.setContent(paramMap.get("comment"));
        pojo.setUserId(UserHolder.getUserId());
        // 调用api添加评论
        commentApi.add(pojo);
    }
}
